package cn.virens.util;

import java.util.Collection;
import java.util.Map;

import cn.virens.exception.APIException;

public class Assert {
	public static <T> T isEmpty(T obj, String message) {
		return isEmpty(obj, "NULL", message);
	}

	public static <T> T isEmpty(T obj, String code, String message) {
		if (obj == null) {
			throw new APIException(code, message);
		} else if (obj instanceof Map && ((Map<?, ?>) obj).isEmpty()) {
			throw new APIException(code, message);
		} else if (obj.getClass().isArray() && ((Object[]) obj).length == 0) {
			throw new APIException(code, message);
		} else if (obj instanceof Collection && ((Collection<?>) obj).isEmpty()) {
			throw new APIException(code, message);
		} else if (obj instanceof CharSequence && ((CharSequence) obj).length() == 0) {
			throw new APIException(code, message);
		} else {
			return obj;
		}
	}

	public static <T> T isNull(T obj, String message) {
		return isNull(obj, "NULL", message);
	}

	public static <T> T isNull(T obj, String code, String message) {
		if (obj == null) {
			throw new APIException(code, message);
		} else {
			return obj;
		}
	}
}
